<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/28
 * Time: 11:19
 */

namespace Qwadmin\Controller;

class StatisticsController extends ComController {
    
	/**
	* 7日数据表
	**/
	function daylog(){
		$day=strtotime(date('Y-m-d',time()));
		$day_h=strtotime(date('Y-m-d H',time()));//当前小时
		$h_data=[
			[
				'hour'=>'',
				'day1'=>'',
				'day2'=>'',
				'day3'=>'',
				'day4'=>'',
				'day5'=>'',
				'day6'=>'',
				'day7'=>'',
			]
		];
		
		$h_hours=['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','总计'];
		foreach($h_hours as $key=>$value){
			$h_data[$key+1] = [
				'hour'=>$value,
				'day1'=>'',
				'day2'=>'',
				'day3'=>'',
				'day4'=>'',
				'day5'=>'',
				'day6'=>'',
				'day7'=>'',
			];
		}
		for($i=6;$i>=0;$i--){
			$n_day = $day-((6-$i)*24*3600);
			$n_day_str=date('Y-m-d',$n_day);
			$key='day'.($i+1);
			$h_data[0][$key] = $n_day_str;
			//获取这个日期的统计数据
			if($n_day==$day){//当日的数据不读取缓存
				$day_data=$this->getdaylog($n_day,false);
			}else{
				$day_data=$this->getdaylog($n_day);
			}
			foreach($day_data as $day_key => $day_value){
				$i_key=intval($day_key)+1;
				if($day_key=='总计'){
					$i_key=25;
				}
				$h_data[$i_key][$key]=$day_value;
			}
		}
      	foreach($h_data as $key=>$value){
			if($value['hour']!='' && $value['hour']!='总计'){
				$h_data[$key]['hour']=$value['hour'].':00 - '.$value['hour'].':59';
			}
		}
		$this->assign('data',$h_data);
		$this->display();
	}
	
	
	/**
	* 获取统计数据
	**/
	function getdaylog($day,$is_bool=true){
		$daylogcache=S('daycache_'.$day);//查询这天的数据是否缓存
		if(!$is_bool){//不启用缓存
			$daylogcache=false;
		}
		$end_day=$day+(1*24*3600);
		if(empty($daylogcache)){
			$h_data=[];
			$h_hours=['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','总计'];
			foreach($h_hours as $key=>$value){
				if($value == '总计'){
					$h_data[$value]=[
						'recharge_num'=>0,//充值单数
						'recharge_sum'=>0,//充值总金额
						'sum_xs_IP'=>0,
						'sum_IP'=>0,
						'Jump_ratio'=>0,//跳转率
						'ratio'=>0,//转化率
						'register_num'=>0,//注册数
						'subscribe_num'=>0,//关注数
						'r_s_ratio'=>0,//关注率
					];
				}else{
					$h_data[$value]=[
						'IP'=>0,//小说站IP
						'zh_IP'=>0,//小说站IP
						'Jump_ratio'=>0,//跳转率
						'zh_jz_IP'=>0,//小说站截至时间IP
						'recharge_sum'=>0,//充值总金额
						'recharge_jz_sum'=>0,//小说站截至时间充值金额
						'recharge_num'=>0,//充值单数
						'recharge_user'=>[],//充值人数
						'ratio'=>0,//转化率
						'register_num'=>0,//注册数
						'subscribe_num'=>0,//关注数
						'r_s_ratio'=>0,//关注率
					];
				}
			}
			$userrecharge_log=M('userrecharge')
				->field("*")
				->where ("request_time<'{$end_day}' and request_time>= '{$day}' and status=1")
				->order("request_time asc")
				->select();
			foreach($userrecharge_log as $value){
				$h=date('H',$value['request_time']);
				$h_data[$h]['recharge_num']++;
				$h_data[$h]['recharge_sum'] +=$value['money'];
				
				if(!in_array($value['openid'],$h_data[$h]['recharge_user'])){
					$h_data[$h]['recharge_user'][]=$value['openid'];
				}
				$h_data['总计']['recharge_num']++;
				$h_data['总计']['recharge_sum'] +=$value['money'];
			}
			
			$day_log=M('user')
				->field("time,subscribe,integral,uid")
				->where ("time<'{$end_day}' and time>= '{$day}'")
				->order("time asc")
				->select();
			foreach($day_log as $value){
				$h=date('H',$value['time']);
				$h_data[$h]['register_num']++;
				if($value['subscribe']){
					$h_data[$h]['subscribe_num']++;
					$h_data['总计']['subscribe_num']++;
				}
				$h_data['总计']['register_num']++;
				
			}
			//获取其IP
			$day_ip=M('day_ip')
				->field("*")
				->where ("day= '{$day}'")
				->order("hour asc")
				->select();
			foreach($day_ip as $value){
				$h=$value['hour'];
				$h_data[$h]['IP']=$value['ip'];//小说站IP
				if(empty($h_data[$h]['zh_jz_IP'])){
					$d_h=intval($h)-1;
					if($d_h<10){
						$d_h='0'.$d_h;
					}
					$h_data[$h]['zh_jz_IP']=isset($h_data[$d_h]['zh_jz_IP'])?$h_data[$d_h]['zh_jz_IP']:0;
				}
				$h_data[$h]['zh_IP']=$value['zh_ip'];//转化平台总IP
				$h_data[$h]['zh_jz_IP'] += $value['zh_ip'];
				if(!isset($h_data['总计']['sum_IP'])){
					$h_data['总计']['sum_IP']=0;
				}
				if(!isset($h_data['总计']['sum_xs_IP'])){
					$h_data['总计']['sum_xs_IP']=0;
				}
				$h_data['总计']['sum_xs_IP'] +=$value['ip'];
				$h_data['总计']['sum_IP'] +=$value['zh_ip'];
			}
			$recharge_jz_sum=0;
			foreach($h_data as $key=>$value){
				$h_data[$key]['r_s_ratio']=sprintf("%.2f",($value['subscribe_num']/$value['register_num'])*100).'%';
				
				if($key=='总计'){
					$h_data[$key]['ratio']=sprintf("%.2f",($value['recharge_sum']/$value['sum_IP'])*100).'分';
					$h_data[$key]['Jump_ratio']=sprintf("%.2f",($value['register_num']/$value['sum_IP'])*100).'%';//跳转率
					continue;
				}
				$h_data[$key]['Jump_ratio']=sprintf("%.2f",($value['register_num']/$value['zh_IP'])*100).'%';//跳转率
				$h_data[$key]['ratio']=sprintf("%.2f",($value['recharge_sum']/$value['zh_IP'])*100).'分';
				$h_data[$key]['recharge_user']=count($value['recharge_user']);
				//统计每小时充值总额
				$recharge_jz_sum += $value['recharge_sum'];
				$h_data[$key]['recharge_jz_sum'] = $recharge_jz_sum;
			}
			$now_day=strtotime(date('Y-m-d',time()));
			S('daycache_'.$day,$h_data,($now_day==$day)?1:(3600*24*8));
			$daylogcache=$h_data;
		}
		return $daylogcache;
	}
	/**
	* 添加IP
	**/
	function setdaylogIP(){
		$ip=$_POST['ip'];
		$ip_type=strtolower($_POST['ip_type']);
		$hour=$_POST['hour'];
		$date=strtotime($_POST['date']);
		$day_ip=M('day_ip')
				->field("*")
				->where ("day='{$date}' and hour='{$hour}'")
				->find();
		if(empty($day_ip)){
			M('day_ip')->add(['day'=>$date,'hour'=>$hour,$ip_type=>$ip]);
		}else{
			M('day_ip')->where('id='.$day_ip['id'])->save([$ip_type=>$ip]);
		}
		S('daycache_'.$date,null);
	}
  
  	/**
	* 添加IP
	**/
	function setdaylogallIP(){
		$is_bool=false;
		$date=strtotime($_POST['date']);
		$data=$_POST['data'];
		if(empty($_POST['data'])){
			echo 0;die;
		}
		$data=json_decode($data,true);
		$day_ip=M('day_ip')->where ("day='{$date}'")->select();
		$data_storage=array();
		foreach($day_ip as $value){
			$data_storage[intval($value['hour'])]=[
				'ip'=>$value['ip'],
				'zh_ip'=>$value['zh_ip'],
				'id'=>$value['id']
			];
		}
		$data_add=array();
		foreach($data['zf_ip'] as $key=>$value){
			if(!isset($data_storage[$key])){//添加
				$hour=$key;
				if(intval($key)<10){
					$hour='0'.$key;
				}
				$data_add[]=['day'=>$date,'ip'=>$data['xs_ip'][$key],'zh_ip'=>$value,'hour'=>$hour];
			}else if($value!=$data_storage[$key]['zh_ip'] || $data['xs_ip'][$key]!=$data_storage[$key]['ip']){
				M('day_ip')->where('id='.$data_storage[$key]['id'])->save(['zh_ip'=>$value,'ip'=>$data['xs_ip'][$key]]);
				$is_bool=true;
			}
			
		}
		if(count($data_add)>0){
			M('day_ip')->addAll($data_add);
			$is_bool=true;
		}
		S('daycache_'.$date,null);
		echo $is_bool;
	}
  
  	/**
	* 书籍阅读榜单  每日首次打开自动更新
	**/
	function bookreadlist(){
		$day=strtotime(date('Y-m-d',time()));//今日时间
		$h_data=[
			[
				'day1'=>'',
				'day2'=>'',
				'day3'=>'',
				'day4'=>'',
				'day5'=>'',
				'day6'=>'',
				'day7'=>'',
			]
		];
		for($li_i=1;$li_i<24;$li_i++){
			for($i=1;$i<=7;$i++){
				$h_data[$li_i]['day'.($i)]='&nbsp;';
			}
		}
		for($i=6;$i>=0;$i--){
			$n_day = $day-((6-$i)*24*3600);
			$n_day_str=date('Y-m-d',$n_day);
			$key='day'.($i+1);
			$h_data[0][$key] = $n_day_str;
			
			//获取这个日期的统计数据
			if($n_day==$day){//当日的数据不读取缓存
				$day_data=$this->getbookreadlog($n_day,false);
			}else{
				$day_data=$this->getbookreadlog($n_day);
			}
			foreach($day_data as $day_key => $day_value){
				$i_key=intval($day_key)+1;
				$h_data[$i_key][$key]=$day_value;
			}
		}
		
		$this->assign('data',$h_data);
		$this->display();
	}
	
	
	/**
	* 获取统计数据
	**/
	function getbookreadlog($day,$is_bool=true){
		$bookreadcache=S('S_bookreadlistcache_'.$day);//查询这天的数据是否缓存
		if(!$is_bool){//不启用缓存
			$bookreadcache=false;
		}
		$end_day=$day+(1*24*3600);
		if(empty($bookreadcache)){
			$data_trade = M('trade_record')
                ->field("bookid,count(bookid) as book_num")
                ->where('time >="'.$day.'" and time <"'.$end_day.'"')
                ->group('bookid')
				->limit(100)
                ->select();
			$data_trade1 = M('trade_record_1')
					->field("bookid,count(bookid) as book_num")
					->where('time >="'.$day.'" and time <"'.$end_day.'"')
					->group('bookid')
					->limit(100)
					->select();
					
			$book_list=[];
			foreach($data_trade as $value){
				$book_list[$value['bookid']]=$value['book_num'];
			}
			foreach($data_trade1 as $value){
				if(!isset($book_list[$value['bookid']])){
					$book_list[$value['bookid']]=0;
				}
				$book_list[$value['bookid']] += $value['book_num'];
			}
			unset($data_trade);
			unset($data_trade1);
			
			arsort($book_list);
			$bookid_arr=array_keys($book_list);
			$bookid_arr=array_slice($bookid_arr,0,30);//读取前25位的ID
			$book_list_sort=[];
			if(count($bookid_arr)>0){
				$bookinfo = M('bookinfo')
						->field("id as bookid,book_title")
						->where('id in ('.implode(',',$bookid_arr).')')
						->select();
				$book_title_arr=[];
				foreach($bookinfo as $key=>$value){
					$book_title_arr[$value['bookid']]=$value['book_title'];
				}
				$i=0;
				foreach($book_list as $key=>$value){
					if($i>=25){
						break;
					}
					$i++;
					if(isset($book_title_arr[$key])){
						$book_list_sort[]=$book_title_arr[$key].'('.$key.') <br>销售章节:'.$value;
					}else{
						$book_list_sort[]='****('.$key.') <br>销售章节:'.$value;
					}
					
				}
			}
			$now_day=strtotime(date('Y-m-d',time()));
			S('S_bookreadlistcache_'.$day,$book_list_sort,($now_day==$day)?1:(3600*24*8));
			$bookreadcache=$book_list_sort;
		}
		return $bookreadcache;
	}
	
	/**
	* 日活跃用户统计
	**/
	function activeusers(){
		$day=strtotime(date('Y-m-d',time()));//今日时间
		$h_data=[
			[
				'day'=>'',
				'active'=>'日活用户',
				'recharge_num'=>'充值人数',
				'recharge_money'=>'充值总额',
			]
		];
		for($i=15;$i>=0;$i--){
			$n_day = $day-((15-$i)*24*3600);
			if($n_day >= '1500652800'){
				//获取这个日期的统计数据
				$day_data=$this->getactiveusers($n_day);
				$h_data[]=$day_data;
			}
		}
		$this->assign('data',$h_data);
		$this->display();
	}
	
	function getactiveusers($day){
		$activeuserscache=S('S_activeuserscache_'.$day);//查询这天的数据是否缓存
		$end_day=$day+(1*24*3600);
		if(empty($activeuserscache)){
			//获取当日日活用户数
			$user_count=M("user")->field("uid")
					->where('login_time >="'.$day.'" and login_time <"'.$end_day.'" and time<"'.$day.'"')
                    ->count('uid');
			$data=['day'=>date('Y-m-d',$day),'active'=>$user_count,'recharge_num'=>0,'recharge_money'=>0];
			//获取当日所有充值用户		
			$userrecharge_list=M("userrecharge")->field("go_user.uid,money")
					->join('go_user on go_user.uid=go_userrecharge.uid')
					->where('go_user.time<"'.$day.'" and response_time >="'.$day.'" and response_time <"'.$end_day.'" and status=1')
                    ->select();
			$userrecharge_data = [];
			foreach($userrecharge_list as $value){
				if(!isset($userrecharge_data[$value['uid']])){
					$userrecharge_data[$value['uid']]=0;
				}
				$userrecharge_data[$value['uid']]+=$value['money'];
				$data['recharge_money']+=$value['money'];
			}
			$data['recharge_num']=count($userrecharge_data);
			$now_day=strtotime(date('Y-m-d',time()));
			S('S_activeuserscache_'.$day,$data,($now_day==$day)?1:(3600*24*8));
			$activeuserscache=$data;
		}
		return $activeuserscache;
	}
	
	/**
	* 推广书籍转化列表
	**/
	function spreadbooklist(){
		$this->display();
	}
	
	//获取书籍转化列表
	function getspreadbooklist(){
		$prefix = C("DB_PREFIX");
		$page = $_POST['page'];
        $pageSize = $_POST['rows'];
        $first = $pageSize * ($page - 1);
		$where='1=1';
		$bookname = I('bookname');
		if(!empty($bookname)){
			$bookname = trim(htmlspecialchars(I('bookname')));
			$bookid = intval($bookname);
			$where .= " and (book_title like '%{$bookname}%' or {$prefix}bookinfo.id={$bookid})";
		}
		$book_ret = M('bookspread')->field("{$prefix}bookspread.*,book_title")
								   ->where($where)
								   ->join("{$prefix}bookinfo on {$prefix}bookinfo.id={$prefix}bookspread.bookid")
								   ->limit($first,$pageSize)
								   ->order("recharge_money desc,bookid desc")
								   ->select();
		foreach($book_ret as $key=>$value){
			$book_ret[$key]['access_rate'] = sprintf('%.2f', $value['access_num']/$value['show_ip']*100).'%';
			$book_ret[$key]['reg_rate'] = sprintf('%.2f', $value['reg_num']/$value['show_ip']*100).'%';
			$book_ret[$key]['pay_rate'] = sprintf('%.2f', $value['recharge_money']/$value['show_ip']*100).'%';
		}
		
		$total = M('bookspread')->join("{$prefix}bookinfo on {$prefix}bookinfo.id={$prefix}bookspread.bookid")
								->where($where)
								->count();
        echo '{"total" : '.$total.', "rows" : '.json_encode($book_ret).'}';
	}
	
	//推广平台列表
	function spreadplatform(){
		//平台标识
		$platform_arr = [
							'mrz'	=> '每日赚(朵迈)',
							'mqi'	=> '梦奇(朵迈)',
							'hz'	=> '豪赚(朵迈)',
							'lmt'	=> '流氓兔(朵迈)',
							'rryd'	=> '摩天轮(朵迈)',
							'ly'	=> '稻草人(朵迈)',
							'ywzh'	=> '欲望(朵迈)',
							'hcym'	=> '红尘忆梦(朵迈)',
							'mry'	=> '美人鱼(朵迈)',
							'wrm'	=> '万人迷(婳小说)',
							'yc'	=> '阅潮(婳小说)',
							'lz'	=> '栗子小说(婳小说)',
							'ml'	=> '麋鹿小说(婳小说)',
							'gsc'	=> '过山车(婳小说)',
							'mq'	=> '米奇(婳小说)',
							'yh'	=> '银狐(婳小说)',
							'nl'	=> '神枪手(婳小说)',
							'bz'	=> '暴走日赚(婳小说)',
							'xsm'	=> '小湿妹(婳小说)',
							'wx'	=> '微信推文'
						];
		$starttime=strtotime(date('Y-m-d',time()));
		$endtime=strtotime(date("Y-m-d",strtotime("+1 day")));
		$this->assign('starttime',$starttime);
		$this->assign('endtime',$endtime);
		$this->assign('platform',$platform_arr);
		$this->display();
	}
	//获取推广平台数据
	function getspreadplatform(){
		$prefix = C("DB_PREFIX");
		$page = $_POST['page'];
        $pageSize = $_POST['rows'];
        $first = $pageSize * ($page - 1);
		$where='1=1';
		$bookname = I('bookname');
		$starttime = I('starttime');
		$endtime = I('endtime');
		$platform_bs = I('platform_bs');
		$is_merge = I('is_merge');//是否合并
		if(!empty($bookname)){
			$bookname = trim(htmlspecialchars(I('bookname')));
			$chapeterid = intval($bookname);
			$where .= " and (book_title like '%{$bookname}%' or chapeterid={$chapeterid})";
		}
		if(!empty($starttime)){
			$starttime=strtotime(date('Y-m-d',strtotime($starttime)));
			$where .= " and access_date>='{$starttime}'";
		}
		if(!empty($endtime)){
			$endtime=strtotime(date('Y-m-d',strtotime($endtime)));
			$where .= " and access_date<'{$endtime}'";
		}
		if(empty($starttime) && empty($endtime)){
			$starttime=strtotime(date('Y-m-d',time()));
			$where .= " and access_date>='{$starttime}'";
			$endtime=strtotime(date("Y-m-d",strtotime("+1 day")));
			$where .= " and access_date<'{$endtime}'";
		}
		if(!$is_merge){//数据不合并
			if(!empty($platform_bs)){
				$where .= " and source='{$platform_bs}'";
			}
			
			$book_ret = M('bookspreadinfo')->field("{$prefix}bookspreadinfo.*,book_title")
										   ->where($where)
										   ->join("{$prefix}bookinfo on {$prefix}bookinfo.id={$prefix}bookspreadinfo.bookid")
										   ->limit($first,$pageSize)
										   ->order("access_date desc,recharge_money desc,id desc")
										   ->select();
		}else{
			$book_ret = M('bookspreadinfo')->field("bookid,access_date,SUM(show_ip) as show_ip,sum(access_num) as access_num,sum(reg_num) as reg_num,SUM(recharge_money) as recharge_money,book_title")
										   ->where($where)
										   ->join("{$prefix}bookinfo on {$prefix}bookinfo.id={$prefix}bookspreadinfo.bookid")
										   ->group('bookid')
										   ->limit($first,$pageSize)
										   ->order("access_date desc,recharge_money desc,go_bookspreadinfo.id desc")
									   	   ->select();
		}
		//平台标识
		$platform_arr = [
							'mrz'	=> '每日赚(朵迈)',
							'mqi'	=> '梦奇(朵迈)',
							'hz'	=> '豪赚(朵迈)',
							'lmt'	=> '流氓兔(朵迈)',
							'rryd'	=> '摩天轮(朵迈)',
							'ly'	=> '稻草人(朵迈)',
							'ywzh'	=> '欲望(朵迈)',
							'hcym'	=> '红尘忆梦(朵迈)',
							'mry'	=> '美人鱼(朵迈)',
							'wrm'	=> '万人迷(婳小说)',
							'yc'	=> '阅潮(婳小说)',
							'lz'	=> '栗子小说(婳小说)',
							'ml'	=> '麋鹿小说(婳小说)',
							'gsc'	=> '过山车(婳小说)',
							'mq'	=> '米奇(婳小说)',
							'yh'	=> '银狐(婳小说)',
							'nl'	=> '神枪手(婳小说)',
							'bz'	=> '暴走日赚(婳小说)',
							'xsm'	=> '小湿妹(婳小说)',
							'wx'	=> '微信推文',
							'old'	=> '老用户充值'
						];
		foreach($book_ret as $key=>$value){
			$book_ret[$key]['access_rate'] = sprintf('%.2f', $value['access_num']/$value['show_ip']*100).'%';
			$book_ret[$key]['reg_rate'] = sprintf('%.2f', $value['reg_num']/$value['show_ip']*100).'%';
			$book_ret[$key]['pay_rate'] = sprintf('%.2f', $value['recharge_money']/$value['show_ip']*100).'%';
			$book_ret[$key]['source'] = empty($is_merge)?$platform_arr[$value['source']] . '(' . $value['source'] . ')':'平台合并';
			$book_ret[$key]['access_date'] = date('Y-m-d',$value['access_date']);
		}
		if(!$is_merge){//数据不合并
			$total = M('bookspreadinfo')->join("{$prefix}bookinfo on {$prefix}bookinfo.id={$prefix}bookspreadinfo.bookid")
									->where($where)
									->count();
		}else{
			$total = M('bookspreadinfo')->field('bookid')
										->where($where)
										->join("{$prefix}bookinfo on {$prefix}bookinfo.id={$prefix}bookspreadinfo.bookid")
										->group('bookid')
										->select();
			$total=count($total);
		}
        echo '{"total" : '.$total.', "rows" : '.json_encode($book_ret).'}';
	}
}
